//currPatient模块名，内部方法调用使用模块名，更改模块名会出错
import $http from "@/static/js/http.js"
import $api from "@/static/js/api.js"

// initial state
const state = () => ({
	dataTimeout: 3600000 *2,//2小时过期
    patientList: [],//当前病人列表，已经过病区过滤
	patientData: [],//所有病人列表
	patientIndex: 0,//病人索引
	wardData: [],//病区列表
	wardIndex: 0,//病区索引
    currPatient: {},//当前病人对象
	page:{//分块读取数据用，number表示已取了几块数据
		// number:1,
		// toltal:1,
		// count:0,
	},
	lastQues:{//上一次请求
		// promise:{},
		// lastTime:""
	},
})

// mutations
const mutations = {
	//读取各项缓存到临时状态
	refreshState(state){
		try {
			let pDataAll = uni.getStorageSync('currPatient_patientData');
			let pData = uni.getStorageSync('currPatient_patientList');
			let wData = uni.getStorageSync('currPatient_wardData');
			let wIdx = uni.getStorageSync('currPatient_wardIndex');
			let pIdx = uni.getStorageSync('currPatient_patientIndex');
			let page = uni.getStorageSync('currPatient_page');
			let lastQues = uni.getStorageSync('currPatient_lastQues');
			if(!pDataAll){//还未获取数据，退出
				console.log("病人数据刷新，但还未获取数据，取消");
				return;
			}
			state.patientList = pData || pDataAll || [];
			state.patientData = pDataAll || [];
			state.wardData = wData || [];
			state.wardIndex = wIdx || 0;
			state.patientIndex = pIdx || 0;
			state.currPatient = state.patientList[pIdx] || {};
			state.page = page || {};
			state.lastQues = lastQues || {};
			// console.log("刷新所有数据完成");
			// console.log(state.patientList);
			// console.log(state.wardData);
			// console.log(state.wardIndex);
			// console.log(state.patientIndex);
			// console.log(state.currPatient);
			console.log("缓存数据刷新完成，最终结果：");
			console.log(state);
		} catch (e) {
		    console.error('当前病人数据刷新失败');
		}
	},
}

// actions
const actions = {
	//查询病人数据，在这里请求服务器，根据token获取数据
	async getPatientData({ state, dispatch, commit },obj,runFlag){
		if($api.isObject(runFlag)){
			runFlag.value = true
		}
		//未请求过数据或数据过期则发起请求，否则取消请求，返回完成状态
		if(!obj.force && state.lastQues.lastTime && Date.now() - state.lastQues.lastTime < state.dataTimeout ){
			if(obj && obj.success){
				obj.success(pRes);
			}
			if(obj && obj.complete){
				obj.complete();
			}
			return
		}
		// console.log("开始查询病人：");
		// console.log(http);
		let pData = [];
		let wData = [{value:'',name:"全部病区"}];
		let patientList = [];
		let wIdx_new = 0; 
		let pIdx_new = 0;
		let pRes = "";//请求的病人数据，用于发送给成功回调
		let quesData = {
			pageNumber: obj.pageNumber || "",
			increment: obj.increment || false,
			validFlag: 1
		}
		
		let questPromise = $http.uquest({
			url: "patient",
			data: quesData,
			success:(res) => {
				if(res.increment){//增量数据，排除重复
					pData = uni.getStorageSync('currPatient_patientData');
					for(let item of res.data){
						if(!$api.arrFind(pData, { key: "patientId", value: item.patientId }) ){
							pData.push(item)
						}
					}
				}else{
					pData = res.data
				}
				pRes = res;
			},
			fail: obj.fail
		});
		let lastQues={
			promise: questPromise,
			quesData: quesData,
			lastTime: Date.now()
		};
		await questPromise;
		if(!pData){//获取失败
			return
		}
		//从病人数据中取出病区数据
		for(let item of pData){
			//顺道计算住院天数
			item.ex_inhospitalDay = $api.dateDiffer(new Date(), item.inhospitalDate);
			item.ex_inhospitalDateStr = $api.dateFormat(item.inhospitalDate,"YYYY-MM-DD");
			item.ex_outhospitalDateStr = $api.dateFormat(item.outhospitalDate,"YYYY-MM-DD");
			item.ex_selowe = item.prepayInAmount - item.selfFeeAmount;
			item.ex_totalInfo = `${item.currentBedNo} 床 ${item.patientName} 住院${item.ex_inhospitalDay}天`;
			
			if(!$api.arrFind(wData, {
				key: "value",
				value: item.currentWardId
			})){
				wData.push({
					value: item.currentWardId,
					name: item.currentWardName
				});
			}
		}
		
		//有旧病人ID和旧病区ID，比对更新后的病人病区ID是否一致，否则病区为全部
		if($api.isValue(obj.patientId) && $api.isValue(obj.wardId)){
			let idx = $api.arrFind(pData, {
				key: "patientId",
				value: obj.patientId,
				format: "index"
			});
			if(pData[idx].currentWardId == obj.wardId){
				wIdx_new = $api.arrFind(wData, {
					key: "value",
					value: obj.wardId,
					format: "index"
				});
				wIdx_new = wIdx_new > -1 ? wIdx_new : 0;
			}
		}
		
		//用当前病区过滤病人数据
		patientList = $api.arrFilt(pData, {
			key: "currentWardId",
			value: wData[wIdx_new].value,
		});
		
		//如果有旧病人ID，查找病人在新列表索引
		if($api.isValue(obj.patientId)){
			pIdx_new = $api.arrFind(pData, {
				key: "patientId",
				value: obj.patientId,
				format: "index"
			});
			pIdx_new = pIdx_new > -1 ? pIdx_new : 0;
		}
		// console.log("病人数据",pData);
		//写入病区数据
		uni.setStorageSync('currPatient_wardData', wData);
		uni.setStorageSync('currPatient_wardIndex', wIdx_new);
		//写入病人数据
		uni.setStorageSync('currPatient_patientData', pData);
		uni.setStorageSync('currPatient_patientList', patientList);
		uni.setStorageSync('currPatient_patientIndex', pIdx_new);
		//写入信息
		uni.setStorageSync('currPatient_page', {number: pRes.pageNo, toltal: pRes.allPage, count:pRes.count});
		uni.setStorageSync('currPatient_lastQues', lastQues);
		
		//刷新临时状态
		commit('refreshState');
		//过程成功
		if(obj && obj.success){
			obj.success(pRes);
		}
		if(obj && obj.complete){
			obj.complete();
		}
		if($api.isObject(runFlag)){
			runFlag.value = false
		}
	},
	//变更病区索引，过滤病人列表写入临时缓存，data为病区索引号，新病区病人索引号置0
	changeWard({ commit },obj){
		try {
			let wData = uni.getStorageSync('currPatient_wardData');
		    let pData = uni.getStorageSync('currPatient_patientData');
			let patientList = [];
			let wIdx_new = obj.data || 0;
			//过滤
			patientList = $api.arrFilt(pData, {
				key: "currentWardId",
				value: wData[wIdx_new].value,
			});
			//写入数据
			uni.setStorageSync('currPatient_patientList', patientList);
			uni.setStorageSync('currPatient_wardIndex', wIdx_new);
			uni.setStorageSync('currPatient_patientIndex', 0);
			
			commit('refreshState');
			if(obj.success){
				obj.success();
			}
		}catch(e){
		    console.error('病区索引设置失败');
			if(obj.fail){
				obj.fail();
			}
		}
		if(obj.complete){
			obj.complete();
		}
	},
	changeIndex({ commit },obj){
		try{
			uni.setStorageSync('currPatient_patientIndex', obj.data);
			commit('refreshState');
			if(obj.success){
				obj.success();
			}
		}catch{
			console.error('病人索引设置失败');
			if(obj.fail){
				obj.fail();
			}
		}
		if(obj.complete){
			obj.complete();
		}
	},
	refresh({ commit },obj){
		commit('refreshState');
		if(obj && obj.success){
			obj.success();
		}
	},
}

// getters
const getters = {}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}